package org.sky.sys.controller;

import org.apache.logging.log4j.Logger;
import org.sky.autoconfigure.factory.SkyPropertiesFactory;
import org.sky.exception.ServiceException;
import org.sky.sys.entity.SysUser;
import org.sky.sys.entity.SysWidget;
import org.sky.sys.service.SysService;
import org.sky.sys.service.SysWidgetService;
import org.sky.sys.util.BspUtils;
import org.sky.sys.util.MenuVo;
import org.sky.util.JsonUtils;
import org.sky.util.LogUtils;
import org.sky.util.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

/**
 * @author weifx
 * @Title: SysController
 * @ProjectName springboot-platform
 * @Description: TODO系统控制层
 * @date 2019/2/10 21:22
 * @Version 1.0
 */
@Controller
public class SysController {
    private static final Logger log = LogUtils.getLogger(SysController.class);
    @Autowired
    private SysService sysService;
    @Autowired
    private SessionRegistry sessionRegistry;
    @Autowired
    private SysWidgetService sysWidgetService;
    @Autowired
    @Qualifier("captchaProducer")
    private Producer captchaProducer;
    @Autowired
    @Qualifier("captchaProducerMath")
    private Producer captchaProducerMath;
    /**
     * 首页
     * @return
     */
    @GetMapping("/")
    public ModelAndView index(){
        ModelAndView mv = new ModelAndView();
        mv.addObject("captchaEnabled", SkyPropertiesFactory.getSkyProperties().isCaptchaEnabled());
        mv.addObject("captchaType", SkyPropertiesFactory.getSkyProperties().getCaptchaType());
        mv.setViewName("login");
        return mv;
    }

    /**
     * 登录页
     * @return
     */
    @GetMapping("/login")
    public ModelAndView login(){
        ModelAndView mv = new ModelAndView();
        mv.addObject("captchaEnabled", SkyPropertiesFactory.getSkyProperties().isCaptchaEnabled());
        mv.addObject("captchaType", SkyPropertiesFactory.getSkyProperties().getCaptchaType());
        mv.setViewName("login");
        return mv;
    }

    /**
     * 单点登录
     * @return
     */
    @GetMapping("/singleLogin/{username}/{password}")
    public ModelAndView singleLogin(
            @PathVariable String username,
            @PathVariable String password){
        ModelAndView mv = new ModelAndView();
        mv.addObject("username",username);
        mv.addObject("password",password);
        mv.setViewName("singleLogin");
        return mv;
    }

    /**
     * 登录成功请求
     * @return
     */
    @GetMapping("/loginSuccess")
    public ModelAndView loginSuccess(){
        ModelAndView mv = new ModelAndView();
        SysUser loginUser = BspUtils.getLoginUser();
        mv.addObject("loginUser",loginUser);
        List<MenuVo> menuVos = sysService.getLeftNavMenuData();
        mv.addObject("menuVos",menuVos);
        mv.setViewName("main/main");
        return mv;
    }
    /**
     * 工作台
     * @return
     */
    @GetMapping(value = "/sys/workbench")
    public ModelAndView workbench() {
        String userCode=BspUtils.getLoginUser().getCode();
        List<SysWidget> list = sysWidgetService.selectSysWidgetListByUserCode(userCode);
        ModelAndView mv =  new ModelAndView();
        mv.addObject("widgetList", JsonUtils.obj2json(list));
        mv.setViewName("main/workbench");
        return mv;
    }
    /**
     * 打开修改密码页面
     * @return
     */
    @GetMapping(value = "/sys/initUpdatePwdPage")
    public String initUpdatePwdPage(){
        return "main/updatepwd";
    }

    /**
     *  修改密码
     * @param request
     * @return
     */
    @PostMapping(value = "/sys/saveUpdatePwd",produces = "text/html;charset=UTF-8")
    public @ResponseBody String saveUpdatePwd(HttpServletRequest request){
        String password = request.getParameter("password");
        String password1 = request.getParameter("password1");
        String password2 = request.getParameter("password2");
        Result result = null;
        try {
            sysService.saveUpdatePwd(password, password1, password2);
            result = Result.success("修改成功",null,null);
        }catch (ServiceException e){
            result = Result.error("修改失败"+e.getMessage(),e.getMessage(),null);
        }
        return JsonUtils.obj2json(result);
    }

    /**
     * 下载模板文件
     * @param request
     * @param response
     * @param type
     * @param filename
     */
    @GetMapping(value = "/sys/templates/{type}/{filename}",produces = "application/json;charset=UTF-8")
    public void downLoadFile(HttpServletRequest request, HttpServletResponse response,
                             @PathVariable String type,@PathVariable String filename
                            ){
        InputStream fis = null;
        OutputStream os = null;
        try{
            String targetFile = "templates"+File.separator+type+File.separator+filename;
            String filerealpath = SysController.class.getClassLoader().getResource(targetFile).getPath();
            File file = new File(filerealpath);
            fis = new BufferedInputStream(new FileInputStream(filerealpath));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            response.reset();
            // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
            setFileDownloadHeader(request, response, filename);
            os = new BufferedOutputStream(response.getOutputStream());
            os.write(buffer);// 输出文件
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.error("文件下载失败:{}",e.getMessage());
        }finally {
            try {
                if(null!=fis) {
                    fis.close();
                }
                if(null!=os) {
                    os.flush();
                }
                if(null!=os) {
                    os.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    /**
     * 设置让浏览器弹出下载对话框的Header. 根据浏览器的不同设置不同的编码格式 防止中文乱码
     *
     * @param fileName
     *            下载后的文件名.
     */
    private static void setFileDownloadHeader(HttpServletRequest request,
                                              HttpServletResponse response, String fileName) {
        try {
            // 中文文件名支持
            String encodedfileName = null;
            String agent = request.getHeader("USER-AGENT");
            if (null != agent && -1 != agent.indexOf("MSIE")) {// IE
                encodedfileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
                encodedfileName = new String(fileName.getBytes("UTF-8"),
                        "iso-8859-1");
            } else {
                encodedfileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            }
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + encodedfileName + "\"");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    @GetMapping(value = "/sys/captchaImage/{type}/{random}",produces = "image/jpg")
    public @ResponseBody byte[] getKaptchaImage(
            @PathVariable String type, @PathVariable double random,
            HttpServletRequest request, HttpServletResponse response){
        byte[] imgByte = null;
        try{
            HttpSession session = request.getSession();
            String capStr = null;
            String code = null;
            BufferedImage bi = null;
            if ("math".equals(type)){
                String capText = captchaProducerMath.createText();
                capStr = capText.substring(0, capText.lastIndexOf("@"));
                code = capText.substring(capText.lastIndexOf("@") + 1);
                bi = captchaProducerMath.createImage(capStr);
            }
            else if ("char".equals(type)){
                capStr = code = captchaProducer.createText();
                bi = captchaProducer.createImage(capStr);
            }
            session.setAttribute(Constants.KAPTCHA_SESSION_KEY, code);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", os);
            imgByte = os.toByteArray();
            os.close();
            return imgByte;
        }
        catch (Exception e){
            log.error("验证码生成错误:{}",e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}
